// 引入数据库实例
const db = require("../utils/mysql.js");
// 引入验证参数是否为空的模块
const v = require("../utils/verify")
const v2 = require("../utils/verify2")
// 引入sql工具
const doSql = require("../utils/doSql.js")
const doInsert = doSql.insert;
const doUpdate = doSql.updata;
const doQuery = doSql.query;

// 根据用户名获取所有标签
exports.queryAllTag = async (req, res) => {
	const sql = `select tag_id,tag_name from tag where exist = 1`
	try {
		let results = await doQuery(sql)
		res.sd(results);
	} catch (e) {
		res.sdErr(e)
	}
}

// 修改标签
exports.setTag = async (req, res) => {
	if (v2(req, ["tag_id", "tag_name"], res) !== 0) {
		return;
	}
	let tag_name = req.body.tag_name;
	let tag_id = req.body.tag_id;
	const sql = `
	UPDATE blogs.tag t
	SET t.tag_name = ?
	WHERE t.tag_id = ?;
	`
	try {
		await doUpdate(sql, [tag_name, tag_id]);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}

};

// 添加文章标签
exports.addArtTag = async (req, res) => {
	if (v2(req, ["tag_name"], res) !== 0) {
		return;
	}
	let tag_name = req.body.tag_name;
	const sql = `
	insert into tag set ?
	`
	try {
		await doInsert(sql, { tag_name, exist: 1 });
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}

};
// 删除标签
exports.delArtTag = async (req, res) => {
	if (v2(req, ["tag_id"], res) !== 0) {
		return;
	}
	let tag_id = req.body.tag_id;
	const sql = `
	update tag set exist = 0 where tag_id = ?;
	`
	try {
		await doUpdate(sql, [tag_id]);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}

};

// 修改文章标签信息
exports.setArtTag = async (req, res) => {
	if (v2(req, ["article_id", "tag_id"], res) !== 0) {
		return;
	}
	// 首先判断有没有该文章的标签
	let article_id = req.body.article_id;
	let tag_id = req.body.tag_id;
	const sql = `
	select * from tag_art where article_id =?
	`
	try {
		let result = await doQuery(sql, [article_id]);
		if (result.length > 0) {
			// 此文章已经有标签了 只需修改
			const sql1 = `
			update tag_art set tag_id = ? where article_id = ?
			`
			try {
				doUpdate(sql1, [tag_id,article_id])
				res.sd("ok");
			} catch (e) {
				res.sdErr(e);
			}
		} else {
			// 这个文章没有标签 需要插入
			const sql2 = `
			insert into tag_art set ?
			`
			try {
				await doInsert(sql2, { article_id, tag_id })
				res.sd("ok");
			}
			catch (e) {
				res.sdErr(e);
			}

		}
	} catch (e) {
		res.sdErr(e);
	}
};